package com.gack.business.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gack.business.model.StoreCameras;
import com.gack.business.model.VideoStores;
import com.gack.business.repository.VideoStoresRepository;

/**
 * 
* @ClassName: StoreCameraDao 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author (ZhangXinYu)  
* @date 2018年7月11日 下午2:55:51 
* @version V1.0
 */
@Repository
public class StoreCameraDao {
	
	@Autowired
	private EntityManager entityManager;
	@Autowired
	private VideoStoresRepository storeRepository;
	
	// 根据用户查询摄像头列表
	@SuppressWarnings("unchecked")
	public StoreCameras getUserCanUseCameras(String userid){
		List<StoreCameras> cameras = null;
		String jpql = "select"
						+ " *"
					+ " from"
						+ " store_cameras"
					+ " where store_id in"
							+ " ("
							+ "select"
								+ " o.store_id"
							+ " from orders o"
							+ " left join stores s on o.store_id = s.id"
							+ " where o.status = '4'"
								+ " and o.user_id = :userid"
							+ ")"
					+ " and is_use <> 2";
		Query query = entityManager.createNativeQuery(jpql, StoreCameras.class);
		query.setParameter("userid", userid);
		cameras = query.getResultList();
		for (StoreCameras camera : cameras) {
			VideoStores stores = storeRepository.findOne(camera.getStoreId());
			if(stores != null){
				camera.setStoreName(stores.getStoreName());
			}
		}
		return cameras != null && cameras.size() > 0 ? cameras.get(0) : null;
	}
	
	//查询门店下摄像头列表
	@SuppressWarnings("unchecked")
	public StoreCameras getStoreCameras(String sotreid){
		List<StoreCameras> cameras = null;
		String jpql = "select * from store_cameras where store_id = :storeid and is_use <> 2";
		Query query = entityManager.createNativeQuery(jpql, StoreCameras.class);
		query.setParameter("storeid",sotreid);
		cameras = query.getResultList();
		for (StoreCameras camera : cameras) {
			VideoStores stores = storeRepository.findOne(camera.getStoreId());
			if(stores != null){
				camera.setStoreName(stores.getStoreName());
			}
		}
		return cameras != null && cameras.size() > 0 ? cameras.get(0) : null;
	}
	
	//查询摄像头的涉及用户
	@SuppressWarnings("unchecked")
	public List<String> getUserIdByCameraId(String cameraId){
		List<String> userids = null;
		String jpql = "select"
						+ " user_id"
					+ " from"
						+ " orders"
					+ " where store_id in "
						+ "("
						+ "select"
							+ " store_id"
						+ " from store_cameras"
						+ " where id = :cameraId)"
					+ " and status not in ('2','3','5','6','7','8','9','10')";
		Query query = entityManager.createNativeQuery(jpql);
		query.setParameter("cameraId", cameraId);
		userids = query.getResultList();
		return userids;
	}
	
}
